package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.TuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Autowired
    private ReportService reportService;
    @Autowired
    private TuService tuService;


    @GetMapping("/getMemberReport")
    public Result huiyuanshuliang() {
        log.info("前端请求会员数量");
        //做一个map用来封装返回的数据
        HashMap<String, Object> map = new HashMap<>();
        //先用一个集合来装每次拿出来的月份
        ArrayList<String> months = new ArrayList<>();
        //先搞需要的月份
        //先做一个时间标准，便于人看
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM");
        Calendar calendar = Calendar.getInstance();
        //显示的是自己电脑当前时间
        //System.out.println("时间:"+simpleDateFormat.format(calendar.getTime()));
        //1则代表的是对年份操作，2是对月份操作，3是对星期操作，5是对日期操作，11是对小时操作，12是对分钟操作，13是对秒操作，14是对毫秒操作
        //根据需求我们要对月份操作，所以选择Calendar.MONTH，第二个参数是减去指定的时间或者加上
        calendar.add(Calendar.MONTH, -42);
        for (int i = 0; i < 12; i++) {
            months.add(simpleDateFormat.format(calendar.getTime()));
            calendar.add(Calendar.MONTH, +1);
        }
        //把拿到的月份集合放到map里
        map.put("months", months);
        //然后再根据月份拿到这个月注册的人数
        ArrayList<Integer> chaxionghuiyuanshuliang = tuService.chaxionghuiyuanshuliang(months);
        map.put("memberCount", chaxionghuiyuanshuliang);
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    @GetMapping("/getSetmealReport")
    public Result taochanzhanbi() {
        log.info("前端请求套餐占比");
        //返回还是用map
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<String> names = new ArrayList<>();
        //查询出套餐占比
        List<Map<String, Object>> taochanmingcheng = tuService.chaciongtaochanzhanbi();
        //遍历，把套餐名字拿出来先放到setmealNames里
        for (Map<String, Object> name : taochanmingcheng) {
            names.add((String) name.get("name"));
        }
        map.put("setmealNames", names);
        map.put("setmealCount", taochanmingcheng);
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String,Object> map = reportService.getBusinessReportData();
        return new Result(true,MessageConst.GET_BUSINESS_REPORT_SUCCESS,map);
    }
    @RequestMapping("/exportBusinessReport")
    public Result daoChu( HttpServletResponse response) throws IOException {
        log.info("[导出运营数据报表]开始");
        Map<String, Object> reportData = reportService.getBusinessReportData();
        log.debug("[导出运营数据报表]rpc rsp:{}", reportData);
// 取出返回结果
        String reportDate = (String) reportData.get("reportDate");
// 获取会员相关数据
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Long totalMember = (Long) reportData.get("totalMember");
// 获取预约相关数据
        Long todayOrderNumber = (Long) reportData.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) reportData.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) reportData.get("thisMonthOrderNumber");
// 获取到诊相关数据
        Long todayVisitsNumber = (Long) reportData.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) reportData.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) reportData.get("thisMonthVisitsNumber");
// 获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");
        //2-读取模板构造workBook
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
             Workbook workbook = new XSSFWorkbook(is);
             OutputStream os = response.getOutputStream()) {
            Sheet sheet = workbook.getSheetAt(0);
            //3-填入数据
            //日期
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            //会员统计数据
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约到诊数据统计
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            //热门套餐
            int rowNum = 12;
            for (Map setMeal : hotSetmeal) {
                Row row = sheet.getRow(rowNum);
                row.getCell(4).setCellValue((String) setMeal.get("name"));
                row.getCell(5).setCellValue((Long) setMeal.get("setmeal_count"));
                row.getCell(6).setCellValue(((BigDecimal) setMeal.get("proportion")).doubleValue());
                rowNum++;
            }

            //4-写入网络输出流
            //写入返回流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");
            workbook.write(os);
            return null;
        } catch (IOException e) {
            log.error("",e);
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }
}
